package com.biostime.qdingding.modules.qd.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.biostime.qdingding.common.api.FastResponse;
import com.biostime.qdingding.common.api.ListResponse;
import com.biostime.qdingding.common.api.ObjResponse;
import com.biostime.qdingding.common.config.Global;
import com.biostime.qdingding.common.web.BaseController;
import com.biostime.qdingding.modules.qd.api.dto.ActivityDetailDto;
import com.biostime.qdingding.modules.qd.api.dto.AssessComment;
import com.biostime.qdingding.modules.qd.api.dto.CommentDto;
import com.biostime.qdingding.modules.qd.api.dto.VersionUpdateDto;
import com.biostime.qdingding.modules.qd.entity.Activity;
import com.biostime.qdingding.modules.qd.entity.Album;
import com.biostime.qdingding.modules.qd.entity.Comment;
import com.biostime.qdingding.modules.qd.service.ActivityService;
import com.biostime.qdingding.modules.qd.service.AlbumService;
import com.biostime.qdingding.modules.qd.service.AppVersionService;
import com.biostime.qdingding.modules.qd.service.CommentService;
import com.biostime.qdingding.modules.qd.service.MemberService;
import com.github.pagehelper.PageHelper;


/**
 * 活动模块
 * 
 * @author chenweicheng
 * @version 2015-12-10
 */
@RestController
@RequestMapping(value = "${adminPath}/qd/api/activity")
public class ActivityApi extends BaseController{
	
	@Autowired
	private ActivityService activityService;
	
	@Autowired
	private AlbumService albumService;
	
	@Autowired
	private CommentService commentService;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private AppVersionService versionService;
	
	/**
	 * 活动轮播图
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "scrollActivity")
	public ListResponse<HashMap<String, Object>> scrollActivity(String userId,String studentId,String centerId) {
		String message = null;
		List<HashMap<String,Object>>  list = new ArrayList<HashMap<String,Object>>();	
		if(studentId != null && studentId.equals(String.valueOf(BasicApi.defaultStudentId))){
			centerId = null;
		}
		list = activityService.activityScollImage(userId,centerId);
		
		for(int i = 0;i<list.size();i++){		
			//活动图片
			List<Album> album = albumService.apiGet("activity",String.valueOf(list.get(i).get("id")));
			if(album != null && !album.isEmpty()){
				String str = album.get(0).getOrginPath();
				 list.get(i).put("url", str);			

			}
			if(list.get(i).get("collectState").equals("0")){
				list.get(i).put("collectState", null);
			}
			if(list.get(i).get("enrollState").equals("0")){
				list.get(i).put("enrollState", null);
			}			
			
		}
		
		if (userId != null && !userId.equals("")) {
			message = "获取轮播图成功";
		} else {
			message = "获取轮播图失败,参数不全";
		}
		
		return  FastResponse.create().errMsg(message).list(list);
		
	}
	
	/**
	 * 获取活动详情dto
	 * 用于ajax请求
	 * @param id
	 * @return
	 */
	@RequestMapping("getActivityDto")
	public ActivityDetailDto getActivityDto(HttpServletRequest request){
		String activityId = request.getParameter("activityId");
	    String userId = request.getParameter("userId");
		ActivityDetailDto activity = activityService.apiGetActivity(activityId,userId);
		
		//用户id
		if(userId != null && !userId.equals("")){
			activity.setUserId(Integer.parseInt(userId));			
		}
		
		//获取收藏人的头像列表
		List<String> list = activityService.apiGetImgs(activityId);
		List<String> list2 = new ArrayList<String>();
		if(list != null && !list.isEmpty()){
			for(String str : list){
				str =  "http://"+Global.getConfig("domain")+"/qdingding-webapp/cdn/image/"+str;
				list2.add(str); 
			}			
		}
		activity.setHeadImages(list2);
		
		return activity;
	}
		
	/**
	 * 获取活动详情
	 * @param id
	 * @return
	 */
	@RequestMapping("activityDetail")
	public ModelAndView activityDetail(HttpServletRequest request){
	
		String activityId = request.getParameter("activityId");
		String userId = request.getParameter("userId");
		String type = request.getParameter("type");
		//获取活动详情
		ModelAndView modelAndView = new ModelAndView();
		ActivityDetailDto activity = activityService.apiGetActivity(activityId,userId);
		
		//获取收藏人的头像列表
		List<String> list = activityService.apiGetImgs(activityId);
		List<String> list2 = new ArrayList<String>();
		if(list != null && !list.isEmpty()){
			for(String str : list){
				str =  "http://"+Global.getConfig("domain")+"/qdingding-webapp/cdn/image/"+str;
				list2.add(str);
			}			
		}
		activity.setHeadImages(list2);
		
		//获取收藏人数
		int number = activityService.apiGetNumber(activityId);
		activity.setCollectNumber(number); 
		
		//活动图片
		List<Album> album = albumService.apiGet("activity", activityId);
		if(album != null && !album.isEmpty()){
			if(activity != null){
				String str = album.get(0).getOrginPath();
				activity.setImage( "http://"+Global.getConfig("domain")+"/qdingding-webapp/cdn/image/"
						+str);
			}
		}
		
		//评论列表
		List<CommentDto> commentList = commentService.apiActivityComments(activityId,userId);
		if(commentList != null){
			if(!commentList.isEmpty()){
				for(CommentDto dto : commentList){
					
					//评论图片列表
					List<Album> commentAlbum = albumService.apiGet("activityComment", String.valueOf(dto.getId()));	
					if(commentAlbum != null && !commentAlbum.isEmpty()){
						for(Album album1 : commentAlbum){
							album1.setOrginPath( "http://"+Global.getConfig("domain")+"/qdingding-webapp/"
									+ "cdn/image/"+album1.getOrginPath()); 		
							album1.setThumbPath( "http://"+Global.getConfig("domain")+"/qdingding-webapp/"
									+ "cdn/image/"+album1.getThumbPath()); 									
						}					
					}
					dto.setImages(commentAlbum); 
					
					//头像列表
					List<Album> headAlbum = albumService.apiGet("headImg", String.valueOf(dto.getUserId()));
					if(headAlbum != null && !headAlbum.isEmpty()){
						dto.setHeadImg( "http://"+Global.getConfig("domain")+"/qdingding-webapp/cdn/image/"
								+headAlbum.get(0).getOrginPath()); 
					}
					
				}
			}else{
				commentList = null;
			}
		}
				
		//活动介绍url
		String projectUrl = request.getRequestURI();
		String url[] = projectUrl.split("/");
		if(url.length>3){
			projectUrl = url[0]+"/"+url[1]+"/"+url[2];
		}
		String serverUrl = "http://"+Global.getConfig("domain")+"/qdingding-webapp"+Global.getConfig("adminPath")+
				"/qd/activity/show/"+activity.getId();
		activity.setDetailUrl(serverUrl); 
		
		//是否为分享页面
		if(type != null){
			activity.setType(type); 
		}
		
		//用户id
		if(userId != null && !userId.equals("")){
			activity.setUserId(Integer.parseInt(userId));			
		}
		
		if(type.equals("share")){
			
			//苹果版本更新链接
			List<VersionUpdateDto>  dtos = versionService.apiGetVersion("ios");
			if(dtos != null && !dtos.isEmpty()){
				activity.setIosUpdateUrl(dtos.get(0).getUpdateUrl());
			}	
			
			//安卓版本更新链接
			List<VersionUpdateDto>  dto2s = versionService.apiGetVersion("android");
			if(dto2s != null && !dto2s.isEmpty()){
				activity.setAndroidUpdateUrl(dto2s.get(0).getUpdateUrl());
			}				
		}
		
		modelAndView.addObject("activity", activity);
		modelAndView.addObject("commentList",commentList);
		modelAndView.setViewName("modules/qd/activityDetail");
		
		return modelAndView;
	}
	
	/**
	 * 获取活动列表
	 */
	@RequestMapping(value = "activityList")
	public ListResponse<ActivityDetailDto> activityList(String userId, String centerId,int pageindex,int pagesize) {	
		String message = null;
		List<ActivityDetailDto>  activityList = new ArrayList<ActivityDetailDto>();
		int errCode = 0;
		if (userId != null && !userId.equals("")) {
			PageHelper.startPage(pageindex, pagesize);
			activityList = activityService.apiFindList(userId, centerId);
			
			//活动图片
			for(ActivityDetailDto dto :activityList){
				List<Album> album = albumService.apiGet("activity", String.valueOf(dto.getId()));
				if(album != null && !album.isEmpty()){
					dto.setImage(album.get(0).getOrginPath()); 
				}	
			} 
						
			message = "获取活动列表成功";
			errCode = 0;
		} else {
			message = "获取活动列表失败，参数有误";
			errCode = 1;
		}
		return FastResponse.create().errMsg(message).errCode(errCode).list(activityList);
	}
	
	/**
	 * 获取活动状态
	 * 收藏，报名状态
	 */
	@RequestMapping("getActivityState")
	public ObjResponse<HashMap<String,Object>> getActivityState(HttpServletRequest request){
		String activityId = request.getParameter("activityId");
	    String userId = request.getParameter("userId");
		String message = null;
		int errCode = 0;
	    HashMap<String,Object> map = null;
		if(userId != null && !userId.equals("") && activityId != null && !activityId.equals("")){	
			map = activityService.selectActState(userId, activityId);
			if(map != null){
				if(map.get("collectState").equals("0")){
					map.put("collectState", null);
				}
				if(map.get("enrollState").equals("0")){
					map.put("enrollState", null);
				}
			}
			message = "获取活动状态成功";
		}else{
			message = "获取活动状态失败，参数不全";
			errCode = 1;
		}
		
		return FastResponse.create().errMsg(message).errCode(errCode).obj(map);
	}	
	
	/**
	 * 获取我的活动列表
	 * 已收藏的 collect，已报名的 enroll
	 */
	@RequestMapping(value = "myActivityList")
	public ListResponse<ActivityDetailDto> myActivityList(HttpServletRequest request,int pageindex,int pagesize) {	
		
		//默认显示已报名的活动列表
		String type = "enroll";
		String message = null;
		String userId = request.getParameter("userId");
		List<ActivityDetailDto>  activityList = new ArrayList<ActivityDetailDto>();
		int errCode = 0;
		if(request.getParameter("type") != null && !request.getParameter("type").equals("")){
			type = request.getParameter("type");
		}
		
		if (userId != null && !userId.equals("") ) {
			PageHelper.startPage(pageindex, pagesize);
			activityList = activityService.apiMyFindList(userId, type);	
			
			//活动图片
			for(ActivityDetailDto dto :activityList){
				List<Album> album = albumService.apiGet("activity", String.valueOf(dto.getId()));
				if(album != null && !album.isEmpty()){
					dto.setImage(album.get(0).getOrginPath()); 
				}	
			} 
			message = "获取我的活动列表成功";
			errCode = 0;
		} else {
			message = "获取我的活动列表失败，参数有误";
			errCode = 1;
		}
		
		return FastResponse.create().errMsg(message).errCode(errCode).list(activityList);
	}	
	
	/**
	 * 收藏活动
	 */
	@RequestMapping(value = "collectActivity")
	public ObjResponse<String> collectActivity(HttpServletRequest request) {	
		
		String message = null;
		int errCode = 0;
		String userId = request.getParameter("userId");
		String activityId = request.getParameter("activityId");
		
		if (userId != null && !userId.equals("")  && activityId != null && !activityId.equals("")) {
			
			//判断是否收藏过活动
			if(activityService.apiFindOrderById(activityId, userId, "collect") == null){
				int i = activityService.apiInsertActivity(activityId, "collect",userId);
				if(i != 0){
					message = "收藏活动成功";
					errCode = 0;				
				}				
			}else{
				message = "收藏活动失败，您已收藏过该活动";
				errCode = 0;		
			}
			
			
		} else {
			message = "收藏活动，参数有误";
			errCode = 1;
		}
		return FastResponse.create().errMsg(message).errCode(errCode).obj("收藏活动");
	}	
	
	/**
	 * 取消收藏活动
	 */
	@RequestMapping(value = "cancelCollect")
	public ObjResponse<String> cancelCollect(HttpServletRequest request) {	
		
		String message = null;
		int errCode = 0;
		String userId = request.getParameter("userId");
		String activityId = request.getParameter("activityId");
		
		if (userId != null && !userId.equals("") &&	activityId != null && !activityId.equals("")) {
			int i = activityService.apiDeleteOrder(activityId,userId,"collect");
			if(i != 0){
				message = "取消收藏成功";
				errCode = 0;				
			}
		} else {
			message = "取消收藏活动，参数有误";
			errCode = 1;
		}
		
		return FastResponse.create().errMsg(message).errCode(errCode).obj("取消收藏活动");
	}		
	
	/**
	 * 活动报名
	 */
	@RequestMapping(value = "enrollActivity")
	public ObjResponse<String> enrollActivity(HttpServletRequest request) {	
		
		String message = null;
		int errCode = 0;
		String userId = request.getParameter("userId");
		String activityId = request.getParameter("activityId");
		
		if (userId != null && !userId.equals("") && activityId != null && !activityId.equals("")) {
			
			//判断是否报名过活动
			if(activityService.apiFindOrderById(activityId, userId, "enroll") == null){
				int i = activityService.apiInsertActivity(activityId, "enroll",userId);
				if(i != 0){
					message = "报名成功";
					errCode = 0;				
				}
			}else{
				message = "报名失败，您已报名该活动";
				errCode = 1;				
			}
			
		} else {
			message = "报名失败，参数有误";
			errCode = 1;
		}
		
		return FastResponse.create().errMsg(message).errCode(errCode).obj("活动报名");
	}
	
	/**
	 * 取消报名活动
	 */
	@RequestMapping(value = "cancelEnroll")
	public ObjResponse<String> cancelEnroll(HttpServletRequest request) {	
		
		String message = null;
		int errCode = 0;
		String userId = request.getParameter("userId");
		String activityId = request.getParameter("activityId");
		
		if (userId != null && !userId.equals("") &&	activityId != null && !activityId.equals("")) {
			HashMap<String,Object> map = activityService.selectActState(userId, activityId);
			if(map !=null && !map.get("enrollState").equals("unpassed")){
				int i = activityService.apiDeleteOrder(activityId,userId,"enroll");
				if(i != 0){
					message = "取消报名成功";
					errCode = 0;				
				}
			}else{
				message = "取消报名失败，您报名的活动未通过";
				errCode = 1;
			}
		} else {
			message = "取消报名活动，参数有误";
			errCode = 1;
		}
		
		return FastResponse.create().errMsg(message).errCode(errCode).obj("取消报名活动");
	}
	
	/**
	 * 活动评价/发表评价
	 * @Param assessComment
	 */
	@RequestMapping(value = "commentActivity")
	public ObjResponse<String> commentActivity(AssessComment assessComment,HttpServletRequest request) throws Exception {
		int i = 0;
		String message = null;
		String userId = request.getParameter("userId");
		String activityId = request.getParameter("activityId");
		String urls = request.getParameter("urls");
		Map<String, Object> map = new HashMap<String, Object>();
		int errCode = 0;
	
		if (userId != null && !userId.equals("") && activityId != null && !activityId.equals("")) {		
			Activity activity = new Activity();
			Comment comment = new Comment();
			comment.setCategory("activity");
			comment.setObjectId(Integer.parseInt(activityId));
			comment.setReplyId(Integer.parseInt(userId));
						
			//发表活动评论
			if (activity != null) {
				comment.setContent(assessComment.getContent());
				comment.setScore(assessComment.getTotalCommentStar());
				comment.setScore1(assessComment.getEnvironmentCommentStar());
				comment.setScore2(assessComment.getTeacherCommentStar());
				comment.setScore3(assessComment.getServiceCommentStar());  
				comment.setFromIp(commentService.getIpAddress(request));
				if (memberService.apiGet(userId) != null) {
					comment.setReplyName(memberService.apiGet(userId).getNickname());
				}
				i = commentService.apiInsert(comment);

				//插入评论图片
				if (i != 0) {
					if (urls != null && !urls.equals("")) {
						map.put("type", "activity");
						map.put("objectId", comment.getId());
						String picRes = urls.replaceAll(".*\\[", "[").replaceAll("\\].*", "]");
						map.put("picRes", picRes);
						albumService.apiInsertAlbums(map);
					}
					message = "发表评价成功";
					errCode = 0;

				} else {
					message = "发表评价失败";
					errCode = 1;
				}
			} 

		} else {
			message = "发表评价失败，参数不全";
			errCode = 1;
		}

		return FastResponse.create().errMsg(message).errCode(errCode).obj("发表评价");
	}	

	/**
	 * 活动评论列表
	 * 默认页数为1，条数为10
	 * @return
	 */
	@RequestMapping(value = "getActivityComments")
	public List<CommentDto> getActivityComments(HttpServletRequest request) {
		
		//默认页数为1，条数为10
		int pageindex = 1;
		int pagesize = 10;
		String category = null;
		CommentDto commentDto = null;
		List<Album> albumList = null;
		String imageUrl = null;
		String activityId = request.getParameter("activityId");
		String userId = request.getParameter("userId");
		List<CommentDto> commentList = new ArrayList<CommentDto>();
		List<CommentDto> commentList2 = new ArrayList<CommentDto>();		

		if (request.getParameter("pageindex") != null && request.getParameter("pageindex") != null) {
			pageindex = Integer.parseInt(request.getParameter("pageindex"));
			pagesize = Integer.parseInt(request.getParameter("pagesize"));
		}
		
		if (userId != null && !userId.equals("") && activityId != null && !activityId.equals("")) {

			category = "activity";
			PageHelper.startPage(pageindex, pagesize);
			commentList = commentService.apiActivityComments(activityId,userId);
			
			//将commentList，与之对应的图片放进commentDto内
			for (int i = 0; i < commentList.size(); i++) {
				commentDto = commentList.get(i);
				albumList = albumService.apiGet(category, String.valueOf(commentDto.getId()));
				if(!albumService.apiGet("headImg", String.valueOf(commentDto.getUserId())).isEmpty()){
					imageUrl = albumService.apiGet("headImg", String.valueOf(commentDto.getUserId())).get(0).getThumbPath();
				}
				commentDto.setHeadImg((imageUrl)); 
				commentDto.setImages(albumList);
				commentList2.add(commentDto);
			}		
		} 

		return commentList2;
	}
	
}
